#include <iostream>
#include <pthread.h>
#include <unistd.h>

using std::cout;
using std::endl;

struct Data{
    int tickets{20};
    pthread_mutex_t mutex;
};

void *func(void *p)
{
    Data *data = (Data *)p;
    while(1){
        pthread_mutex_lock(&data->mutex);
        if(data->tickets > 0){
            printf("买票前剩余票数：%d\n", data->tickets);
            data->tickets--;
            pthread_mutex_unlock(&data->mutex);
            printf("买票后剩余票数：%d\n", data->tickets);
        }else{
            pthread_mutex_unlock(&data->mutex);
            break;
        }
    }
}

int main(int args, char *argv[])
{
    Data data; 
    pthread_mutex_init(&data.mutex, nullptr);

    pthread_t thid[2];
    pthread_create(&thid[0], nullptr, func, &data);
    pthread_create(&thid[1], nullptr, func, &data);

    pthread_join(thid[0], nullptr); 
    pthread_join(thid[1], nullptr); 


    printf("剩余票数：%d\n", data.tickets);
    return 0;
}